"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : DN主数据文件目录权限修改
Create At   : 2020/12/07
@zou_jialiang0505328126
Description :
    1、主节点执行tpcc，执行过程中进入备节点主数据目录，修改文件所属为root
    2、查看主备节点状态；
    3、主节点连接数据库，功能正常
    4、改回dn1目录文件属组
    5、重启集群
    6、重启成功，备节点状态正常，查询数据一致性
Expect      :
    1、tpcc导入开始，修改属组成功
    2、主机正常，备机unknown
    3、主机连接正常，基本功能正常
    4、属组修改成功
    5、集群重启成功
    6、备机状态正常，与主机数据一致
History     :
    Modified by @wan005 2021/02/26: 备机为非normal状态时，启动可能失败，增加判断
"""

import unittest
import time
from yat.test import macro
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class Chowndn1(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    commonshsta = CommonSH('Standby1DbUser')
    commonshsta2 = CommonSH('Standby2DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case120.py 开始执行------------')
        self.db_primary_db_user = Node(node='PrimaryDbUser')
        self.db_primary_root = Node(node='PrimaryRoot')
        self.db_standby_root = Node(node='Standby1Root')
        self.db_standby1_db_user = Node(node='Standby1DbUser')
        self.db_standby2_db_user = Node(node='Standby2DbUser')
        self.constant = Constant()
        self.common = Common('PrimaryRoot')

    def test_basebackup(self):
        self.log.info('--1、主节点执行tpcc，执行过程中进入备节点主数据目录，修改文件所属为root----')
        self.log.info('============启动TPCC=================')
        tpcc_thread = ComThread(self.common.startTPCC,
                                args=(self.db_primary_root, macro.TPCC_PATH,))
        tpcc_thread.setDaemon(True)
        tpcc_thread.start()

        self.log.info('===========修改dn1属组================')
        time.sleep(2)
        shell_cmd = f"chown root:root {macro.DB_INSTANCE_PATH}"
        self.log.info(shell_cmd)
        result = self.db_standby_root.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('===============检查TPCC结果===============')
        tpcc_thread.join(60 * 60)
        result = tpcc_thread.get_result()
        self.log.info(result)
        self.assertIn(self.constant.TPCC_SUCCESS_MSG, result)

        self.log.info('---------2、查看主备节点状态；--------------')
        result = self.commonshsta.getDbClusterStatus('detail')
        self.log.info(result)
        self.assertIn(self.constant.P_NORMAL, result)
        self.assertIn('S Unknown Unknown', result)

        self.log.info('----------3、主节点连接数据库，功能正常-------')
        result = self.commonshpri.executDbSql(r'\d')
        self.log.info(result)
        self.assertNotIn(self.constant.FAILED_CONNECT_DB, result)

        self.log.info("-------------4、改回dn1目录文件属组-------------")
        shell_cmd = f"chown {self.db_primary_db_user.ssh_user}:" \
            f"{self.db_primary_db_user.ssh_user} {macro.DB_INSTANCE_PATH}"
        self.log.info(shell_cmd)
        result = self.db_standby_root.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info("-----------5、重启集群-------------")
        result = self.commonshpri.stopDbCluster()
        self.log.info(f'result is {result};备节点可能因为dn1属组被修改而已经stop')
        result = self.commonshpri.startDbCluster(True)
        flg = 'Degrade' in result or self.constant.START_SUCCESS_MSG
        self.assertTrue(flg)

        self.log.info("========判断备机是否需要重建=====")
        result = self.commonshpri.check_whether_need_build()
        if result:
            result = self.commonshsta.buildStandby()
            self.log.info(result)
            self.assertIn(self.constant.BUILD_SUCCESS_MSG, result)
            result = self.commonshsta2.buildStandby()
            self.log.info(result)
            self.assertIn(self.constant.BUILD_SUCCESS_MSG, result)

        self.log.info('---------6、重启成功，查询主备数据一致性---------')
        result = self.commonshsta.check_data_consistency()
        self.assertTrue(result)
        result = self.commonshsta2.check_data_consistency()
        self.assertTrue(result)

        self.log.info('--------------------检查数据一致性---------------------')
        nodes_tuple = (self.db_primary_db_user,
                       self.db_standby1_db_user, self.db_standby2_db_user)
        flag = self.common.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)

        table_dict = self.common.format_sql_result(
            self.commonshpri.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.common.check_data_sample_by_all(
                select_sql, *nodes_tuple)
            self.assertTrue(flag)

    def tearDown(self):
        self.log.info('--------------------环境清理----------------')
        self.log.info("---------------恢复dn1目录文件属组----------")
        shell_cmd = f"chown {self.db_primary_db_user.ssh_user}:" \
            f"{self.db_primary_db_user.ssh_user} {macro.DB_INSTANCE_PATH}"
        self.log.info(shell_cmd)
        result = self.db_standby_root.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('------Opengauss_Reliability_Dbsys_Case120.py 执行结束--')